/**
 * 
 */
package pt.mleiria.cryptographic.utils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;

/**
 * @author NB13712
 *
 */
public class BookFrequency {
	private static final String BOOK = "D:/SkyDrive/Documentos/AliceInWonderland.txt"; 
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, Integer> mapWordFrequency = new HashMap<String, Integer>();
		buildFrequencyMap(BOOK, mapWordFrequency);

	}
	
	/**
	 * Constroi um Mapa na forma [palavra, num. de vezes que
         *  ela ocorre no documento]
	 * @param file
	 * @param mapWordFrequency
	 */
	private static void buildFrequencyMap(final String file, Map<String, Integer> mapWordFrequency){
		try{
			Scanner input = new Scanner(new File(file));
			while(input.hasNextLine()){
			    final String line = input.nextLine();
			        StringTokenizer parser = new StringTokenizer(line, ",.;:()-!?' ");
			    while(parser.hasMoreTokens()){
			        final String word = parser.nextToken().toUpperCase();

				Integer listing = mapWordFrequency.get(word);
				if(listing == null){
				    listing = 1;
				}else{
				    listing += 1;
				}
				mapWordFrequency.put(word, listing);
			    }
			}
		input.close();
		String topWord = "";
		Integer topValue = 0;
		for (Map.Entry<String, Integer> entry : mapWordFrequency.entrySet()) {
			//System.out.println("Key : " + entry.getKey() + " Value : "+ entry.getValue());
			if(entry.getValue() > topValue){
				topValue = entry.getValue();
				topWord = entry.getKey();
			}
		}
		System.out.println("Top Word=" + topWord);
		System.out.println("Top Value=" + topValue);
		System.out.println(mapWordFrequency.toString());
		}catch(IOException e){
			System.out.println(e);
		}
	}

}
